package com.m2h.xiaoke.api;


import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.LogUtils;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechUnderstander;
import com.iflytek.cloud.SpeechUnderstanderListener;
import com.iflytek.cloud.TextUnderstanderListener;
import com.iflytek.cloud.UnderstanderResult;
import com.m2h.xiaoke.param.Constants;
import com.m2h.xiaoke.param.VoiceParamManager;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author lijh
 */
public class XunfeiUnderstand {
    private static final String SIGN = "at " + XunfeiUnderstand.class.getSimpleName() + ": ";
    private Context mContext;
    private SpeechUnderstander mSpeechUnderstander;
    private boolean isRunning = false;
    private boolean isUnderStandCancel = false;
    private static XunfeiUnderstand xunfeiUnderstandInstance = null;
    /**
     * 初始化语义理解
     *
     * @param context
     */
    public void init(Context context) {
        LogUtils.d("init Understand");
        this.mContext = context;
        isRunning = true;
        mSpeechUnderstander = SpeechUnderstander.createUnderstander(context, mSpeechUdrInitListener);
    }
    /**
     * 反初始化
     */
    public void uninit() {
        if (null != mSpeechUnderstander) {
            mSpeechUnderstander.cancel();
            mSpeechUnderstander.destroy();
        }
    }

    /**
     * 开启监听
     */
    public void startUnderstand() {
        if (null == mSpeechUnderstander) {
            return;
        }
        if (!mSpeechUnderstander.isUnderstanding()) {
            startUndListen();
        } else {
            Log.d(Constants.TAG, SIGN + "startUnderstanderListen  but isUnderstanding() is true");
            closeUnderstanderListen();
            startUndListen();
        }
    }

    /**
     * 关闭监听
     */
    public void closeUnderstanderListen() {
        if (null != mSpeechUnderstander && mSpeechUnderstander.isUnderstanding()) {
            isUnderStandCancel = true;
            mSpeechUnderstander.cancel();
        }

    }

    public void stopUnderstand() {
        mSpeechUnderstander.stopUnderstanding();
    }

    /**
     * 是否在监听
     *
     * @return
     */
    public boolean isListening() {
        if (null == mSpeechUdrInitListener) {
            return false;
        }
        return mSpeechUnderstander.isUnderstanding();
    }

    private void startUndListen() {
        isUnderStandCancel = false;
        VoiceParamManager.setUnderstanderParam(mSpeechUnderstander);
        Log.d(Constants.TAG, SIGN + "startUnderstanding");
        int ret = mSpeechUnderstander.startUnderstanding(mSpeechUnderstanderListener);
        if (ret != 0) {
            Log.w(Constants.TAG, SIGN + "startUndListen  Error:" + ret);
        }
    }

    public static XunfeiUnderstand getInstance() {
        if (null == xunfeiUnderstandInstance) {
            synchronized (XunfeiUnderstand.class) {
                if (null == xunfeiUnderstandInstance) {
                    xunfeiUnderstandInstance = new XunfeiUnderstand();
                }
            }
        }
        return xunfeiUnderstandInstance;
    }

    /**
     * 语义理解回调。
     */
    private SpeechUnderstanderListener mSpeechUnderstanderListener = new SpeechUnderstanderListener() {
        @Override
        public void onBeginOfSpeech() {
            // 此回调表示：sdk内部录音机已经准备好了，用户可以开始语音输入
            Log.d(Constants.TAG, SIGN + "onBeginOfSpeech()");
        }

        @Override
        public void onEndOfSpeech() {
            Log.d(Constants.TAG, SIGN + "onEndOfSpeech");
        }


        @Override
        public void onResult(UnderstanderResult result) {
            Log.d(Constants.TAG, SIGN + "callback   onResult:" + result.getResultString());
            // 显示
            String text = result.getResultString();
            try {
                JSONObject jsonObject = new JSONObject(text);
                text = jsonObject.getString("text");
            } catch (JSONException e) {
                e.toString();
            }

        }

        @Override
        public void onError(SpeechError error) {
            Log.d(Constants.TAG, SIGN + "onError error_code" + error.getErrorCode());
        }

        @Override
        public void onVolumeChanged(int volume, byte[] data) {

        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
        }
    };


    private TextUnderstanderListener mTextUnderstanderListener = new TextUnderstanderListener() {
        @Override
        public void onResult(final UnderstanderResult result) {
            if (null != result) {
                // 显示
                String text = result.getResultString();
                if (!TextUtils.isEmpty(text)) {
                    LogUtils.d(Constants.TAG, SIGN + "onResult:  " + text);
                }
            } else {
                LogUtils.d(Constants.TAG, SIGN + "understander result:null");
            }
        }

        @Override
        public void onError(SpeechError error) {

        }
    };
    /**
     * 初始化监听器（语音到语义）。
     */
    private InitListener mSpeechUdrInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
            Log.d(Constants.TAG, SIGN + "mSpeechUdrInitListener code = " + code);
            if (code != ErrorCode.SUCCESS) {
                Log.e(Constants.TAG, SIGN + "mSpeechUdrInitListener Error code = " + code);
            } else {
                VoiceParamManager.setUnderstanderParam(mSpeechUnderstander);
            }
        }
    };
}
